package com.speechb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.speechb.entity.KeyValue;
import com.speechb.mapper.KeyValueMapper;
import com.speechb.service.IKeyValueService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 键值对表 服务实现类
 * </p>
 *
 * @author llj
 * @since 2019-09-01
 */
@Service
public class KeyValueServiceImpl extends ServiceImpl<KeyValueMapper, KeyValue> implements IKeyValueService {
    private static final Logger LOGGER = LoggerFactory.getLogger(KeyValueServiceImpl.class);
    @Autowired
    KeyValueMapper keyValueMapper;

    public static final Cache<String, String> CACHE = CacheBuilder
            .newBuilder()
            .maximumSize(1000)
            .expireAfterAccess(1, TimeUnit.DAYS)
            .build();

    @Override
    public void insertKeyValue(String key, String value) {
        CACHE.put(key, value);
        keyValueMapper.insertKeyValue(key,value, null);
    }

    @Override
    public String findValueByKey(String key) {
        String value = CACHE.getIfPresent(key);
        if (StringUtils.isNotEmpty(value)) {
            LOGGER.warn("从缓存中获取");
           return value;
        }
        value = keyValueMapper.findValueByKey(key);
        if (StringUtils.isNotEmpty(value)) {
            CACHE.put(key, value);
            return value;
        }
        return null;
    }

    @Override
    public void deleteByKey(String key) {
        CACHE.invalidate(key);
        keyValueMapper.deleteByKey(key);
    }
}
